package org.example.config.security;

import io.jsonwebtoken.Jwts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.security.Key;

@Configuration
public class SecurityConfig {
    @Bean
    public Key key() {
        return Jwts.SIG.HS256.key().build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity.formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(session -> {
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                })
                .addFilterBefore(new JWTFilter(key()), UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling(exception -> {
                    exception.accessDeniedHandler(new CustomAccessDeniedHandler())
                            .authenticationEntryPoint(new CustomAuthenticationEntryPoint());
                })
                .authorizeHttpRequests(request -> {
                    request.mvcMatchers("/public").permitAll()
                            .mvcMatchers("/profile").authenticated()
                            .mvcMatchers("/admin").hasRole("ADMIN")
                            .mvcMatchers("/token").permitAll()
                            .mvcMatchers("/v3/api-docs","/v3/api-docs.yaml","/swagger-ui.html","/v3/api-docs/swagger-config","/swagger-ui/**").permitAll()
                            .anyRequest().authenticated();
                }).build();
    }
}
